<template>
  <div>
    <!-- 司机列表表格 -->
    <el-table :data="drivers" style="width: 100%">
      <el-table-column prop="id" label="ID" width="100"></el-table-column>
      <el-table-column prop="nickname" label="司机名字" width="100"></el-table-column>
      <el-table-column prop="integral" label="积分" width="100"></el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button @click="showDetails(scope.row)" type="primary" size="small">查看详情</el-button>
          <el-button @click="openAddPoints(scope.row)" type="primary" size="small">添加积分</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 司机详情抽屉 -->
    <el-drawer v-model="showDrawer" title="司机详情" size="50%"  @close="clearOcrData">
      <el-tabs v-model="currentTab" @tab-click="onTabClick">
        <!-- 身份证信息标签页 -->
        <el-tab-pane label="身份证" name="idCard">
          <!-- 身份证正面图片 -->
          <el-image
            v-if="currentDriver.front"
            :src="currentDriver.front"
            fit="contain"
            style="width: 30%; height: 150px; object-fit: contain;"
          ></el-image>
          <!-- 身份证反面图片 -->
          <el-image
            v-if="currentDriver.opposite"
            :src="currentDriver.opposite"
            fit="contain"
            style="width: 30%; height: 150px; object-fit: contain;"
          ></el-image>
          <!-- 身份证信息描述列表 -->
          <el-descriptions :column="1" border>
            <el-descriptions-item label="姓名">{{ idInfo.name }}</el-descriptions-item>
            <el-descriptions-item label="性别">{{ idInfo.sex }}</el-descriptions-item>
            <el-descriptions-item label="民族">{{ idInfo.ethnicity }}</el-descriptions-item>
            <el-descriptions-item label="地址">{{ idInfo.address }}</el-descriptions-item>
            <el-descriptions-item label="身份证号">{{ idInfo.idNumber }}</el-descriptions-item>
            <el-descriptions-item label="颁发机关">{{ idInfo.issueAuthority }}</el-descriptions-item>
            <el-descriptions-item label="有效期限">{{ idInfo.validPeriod }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <!-- 驾驶证信息标签页 -->
        <el-tab-pane label="驾驶证" name="driverLicense">
          <!-- 驾驶证图片 -->
          <el-image
            v-if="currentDriver.driver_front"
            :src="currentDriver.driver_front"
            fit="contain"
            style="width: 60%; height: 200px; object-fit: contain;"
          ></el-image>
          <!-- 驾驶证信息 -->
          <el-descriptions :column="1" border v-if="driverInfo">
            <el-descriptions-item label="姓名">{{ driverInfo.name }}</el-descriptions-item>
            <el-descriptions-item label="性别">{{ driverInfo.sex }}</el-descriptions-item>
            <el-descriptions-item label="国籍">{{ driverInfo.nationality }}</el-descriptions-item>
            <el-descriptions-item label="地址">{{ driverInfo.address }}</el-descriptions-item>
            <el-descriptions-item label="出生日期">{{ driverInfo.birthDate }}</el-descriptions-item>
            <el-descriptions-item label="初次领证日期">{{ driverInfo.initialIssueDate }}</el-descriptions-item>
            <el-descriptions-item label="准驾车型">{{ driverInfo.approvedType }}</el-descriptions-item>
            <el-descriptions-item label="发证机关">{{ driverInfo.issueAuthority }}</el-descriptions-item>
            <el-descriptions-item label="有效期限">{{ driverInfo.validPeriod }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
        <!-- 行驶证信息标签页 -->
        <el-tab-pane label="行驶证" name="vehicleLicense">
          <!-- 行驶证图片 -->
          <el-image
            v-if="currentDriver.driving_front"
            :src="currentDriver.driving_front"
            fit="contain"
            style="width: 60%; height: 200px; object-fit: contain;"
          ></el-image>
          <!-- 行驶证信息 -->
          <el-descriptions :column="1" border v-if="vehicleInfo">
            <el-descriptions-item label="车牌号码">{{ vehicleInfo.licensePlateNumber }}</el-descriptions-item>
            <el-descriptions-item label="车辆类型">{{ vehicleInfo.vehicleType }}</el-descriptions-item>
            <el-descriptions-item label="所有人">{{ vehicleInfo.owner }}</el-descriptions-item>
            <el-descriptions-item label="住址">{{ vehicleInfo.address }}</el-descriptions-item>
            <el-descriptions-item label="使用性质">{{ vehicleInfo.useNature }}</el-descriptions-item>
            <el-descriptions-item label="品牌型号">{{ vehicleInfo.model }}</el-descriptions-item>
            <el-descriptions-item label="车辆识别代号">{{ vehicleInfo.vinCode }}</el-descriptions-item>
            <el-descriptions-item label="发动机号码">{{ vehicleInfo.engineNumber }}</el-descriptions-item>
            <el-descriptions-item label="注册日期">{{ vehicleInfo.registerDate }}</el-descriptions-item>
            <el-descriptions-item label="发证日期">{{ vehicleInfo.issueDate }}</el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>
      </el-tabs>
    </el-drawer>

    <!-- 添加积分对话框 -->
    <el-dialog v-model="showAddPoints" title="添加积分" width="30%">
      <el-form :model="pointsForm">
        <el-form-item label="增加积分数量">
          <el-input-number v-model="pointsForm.points" :min="1" :max="1000"></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddPoints = false">取消</el-button>
          <el-button type="primary" @click="confirmAddPoints">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
  
<script setup>
import { ref, onMounted } from 'vue';
import { getDriver, insertAndUpdateDriver, recognizeDrivingLicense, recognizeVehicleLicense, getRecognizeIdCard } from '@/api/admin';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
const router = useRouter();
import { useTokenStore } from '@/stores/token';

// 定义响应式变量
const uts = useTokenStore();
const drivers = ref([]);
const idInfo = ref({});
const showDrawer = ref(false);
const currentTab = ref('idCard');
const currentDriver = ref({});
const showAddPoints = ref(false);
const pointsForm = ref({
  points: 1
});
const driverInfo = ref(null);
const vehicleInfo = ref(null);

// 清除OCR识别到的数据
const clearOcrData = () => {
  idInfo.value = {};
  driverInfo.value = {};
  vehicleInfo.value = {};
};
// 获取OCR识别结果
const getIdInfo = async (front, opposite) => {
  try {
    const response = await getRecognizeIdCard({ frontImageUrl: front, backImageUrl: opposite });
    if (response.shuju) {
      const frontData = JSON.parse(response.shuju.frontOcrResult);
      const frontData2 = JSON.parse(frontData.body.data);
      const backData = JSON.parse(response.shuju.backOcrResult);
      const backData2 = JSON.parse(backData.body.data);
      
      idInfo.value = {
        name: frontData2.data.face.data.name,
        sex: frontData2.data.face.data.sex,
        ethnicity: frontData2.data.face.data.ethnicity,
        address: frontData2.data.face.data.address,
        idNumber: frontData2.data.face.data.idNumber,
        issueAuthority: backData2.data.back.data.issueAuthority,
        validPeriod: backData2.data.back.data.validPeriod,
      };
    } else {
      console.error('OCR识别失败：没有返回数据');
      ElMessage.error('身份证识别失败，请检查图片质量并重试');
    }
  } catch (error) {
    console.error('OCR识别过程中发生错误:', error);
    ElMessage.error('身份证识别失败，请稍后重试或联系技术支持' );
  }
};

// 获取司机列表数据
const getDrivers = async () => {
  if (uts.token.id === undefined) {
    console.error('未登录或登录已过期');
    ElMessage.error('请先登录');
    router.push('/admin');
    return;
  }
  try {
    const response = await getDriver();
    if (response && response.shuju) {
      drivers.value = response.shuju;
    } else {
      console.error('获取司机数据失败: 响应数据格式不正确');
    }
  } catch (error) {
    console.error('获取司机数据失败:', error);
  }
};

// 查看司机详情
const showDetails = async (driver) => {
  currentDriver.value = driver;
  await getIdInfo(driver.front, driver.opposite); 
  showDrawer.value = true;
};

// 打开添加积分对话框
const openAddPoints = (driver) => {
  currentDriver.value = driver;
  pointsForm.value.points = 1;
  showAddPoints.value = true;
};

// 确认添加积分
const confirmAddPoints = async () => {
  try {
    const updatedDriver = {
      ...currentDriver.value,
      integral: currentDriver.value.integral + pointsForm.value.points
    };
    const response = await insertAndUpdateDriver(updatedDriver);
    if (response && response.flag) {
      ElMessage.success('积分添加成功');
      showAddPoints.value = false;
      await getDrivers(); 
    } else {
      ElMessage.error('积分添加失败');
    }
  } catch (error) {
    console.error('添加积分失败:', error);
    ElMessage.error('添加积分时发生错误');
  }
};

// 处理标签页点击事件
const onTabClick = async (tab) => {
  if (tab.props.name === 'driverLicense') {
    await getDriverLicenseInfo();
  } 
  else if (tab.props.name === 'vehicleLicense') {
    await getVehicleLicenseInfo();
  }
};

// 识别驾驶证信息
const getDriverLicenseInfo = async () => {
  try {
    const response = await recognizeDrivingLicense({
      "imageUrl": currentDriver.value.driver_front
    });
    if (response.shuju) {
      const frontData = JSON.parse(response.shuju.recognitionResult);
      const frontData2 = JSON.parse(frontData.body.data);
      driverInfo.value = {
        name: frontData2.data.face.data.name,
        sex: frontData2.data.face.data.sex,
        nationality: frontData2.data.face.data.nationality,
        address: frontData2.data.face.data.address,
        birthDate: frontData2.data.face.data.birthDate,
        initialIssueDate: frontData2.data.face.data.initialIssueDate,
        approvedType: frontData2.data.face.data.approvedType,
        issueAuthority: frontData2.data.face.data.issueAuthority,
        validPeriod: frontData2.data.face.data.validPeriod,
      };
    } else {
      console.error('OCR识别失败:没有返回数据');
      ElMessage.error('驾驶证识别失败：没有返回数据');
    }
  } catch (error) {
    console.error('OCR识别过程中发生错误:', error);
    ElMessage.error('驾驶证识别失败，请稍后重试或联系技术支持' );
  }
};

// 识别行驶证信息
const getVehicleLicenseInfo = async () => {
  try {
    const response = await recognizeVehicleLicense({
      "imageUrl": currentDriver.value.driving_front
    });
    if (response.shuju) {
      const data = JSON.parse(response.shuju.recognitionResult);
      const vehicleData = JSON.parse(data.body.data);
      vehicleInfo.value = {
        licensePlateNumber: vehicleData.data.face.data.licensePlateNumber,
        vehicleType: vehicleData.data.face.data.vehicleType,
        owner: vehicleData.data.face.data.owner,
        address: vehicleData.data.face.data.address,
        useNature: vehicleData.data.face.data.useNature,
        model: vehicleData.data.face.data.model,
        vinCode: vehicleData.data.face.data.vinCode,
        engineNumber: vehicleData.data.face.data.engineNumber,
        registerDate: vehicleData.data.face.data.registrationDate,
        issueDate: vehicleData.data.face.data.issueDate,
        issueAuthority: vehicleData.data.face.data.issueAuthority
      };
    } else {
      console.error('OCR识别失败:没有返回数据');
      ElMessage.error('行驶证识别失败：没有返回数据');
    }
  } catch (error) {
    console.error('OCR识别过程中发生错误:', error);
    ElMessage.error('行驶证识别失败，请稍后重试或联系技术支持');
  }
};

// 组件挂载时获取司机列表
onMounted(() => {
  getDrivers();
});
</script>
<style scoped>
</style>